var express = require("express");
var router = express.Router();
let crypto = require("crypto");
let userModel = require("../model/user/index");
let jwt = require("jsonwebtoken");
/* GET users listing. */
router.get("/", function (req, res, next) {
  res.send("respond with a resource");
});
router.post("/login",async (req,res,next)=>{

  let  {username,userpwd} = req.body;

  let md5 = crypto.createHash("md5");
  userpwd = md5.update(userpwd).digest("hex");

  let  list  = await userModel.query({username,userpwd});
  if(list.length){
    let info  = list[0];//用户登录成功的信息
    // console.log(info);
    let token  = jwt.sign({_id:info._id,username:info.username,type:info.type},"abc",{expiresIn:60*60*0.5});//单位是秒

    res.json({
      code:1,
      msg:"成功",
      path:info.type==1?"teacher":"student",
      token

    })

  }else{
    res.json({
      code:0,
      msg:"用户和密码不匹配"
    })

  }





})

router.post("/register", async (req, res, next) => {
  let { username, userpwd, type } = req.body;
  //需要把数据写入数据库

  let md5 = crypto.createHash("md5");

  userpwd = md5.update(userpwd).digest("hex");

  //写入数据库

  let result = await userModel.query({ username });

  if (result.length) {
    res.json({
      code: 0,
      msg: "该用户名已经存在",
    });
  } else {
    let list = await userModel.register({ username, userpwd, type });
    if (list.length) {
      res.json({
        code: 1,
        msg: "新增成功",
      });
    } else {
      res.json({
        code: 1,
        msg: "新增失败",
      });
    }
  }
});

module.exports = router;
